"""
活动中心序列化器
用于活动、社团等数据的序列化与反序列化
"""

from rest_framework import serializers
from django.db.models import Count
from .models import Club, ClubMember, Activity, ActivityRegistration, ActivityImage
from users.serializers import UserBriefSerializer


class ClubSerializer(serializers.ModelSerializer):
    """社团序列化器"""
    president_name = serializers.SerializerMethodField()
    member_count = serializers.IntegerField(read_only=True)
    activity_count = serializers.SerializerMethodField()

    class Meta:
        model = Club
        fields = [
            'id', 'name', 'description', 'logo', 'category', 'founded_date',
            'member_count', 'contact_person', 'contact_phone', 'contact_email',
            'status', 'is_verified', 'created_at', 'updated_at',
            'president_name', 'activity_count'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at', 'member_count', 'founded_date', 'is_verified', 'status']
        extra_kwargs = {
            'contact_phone': {
                'required': True,
                'help_text': '请输入11位手机号码'
            },
            'contact_person': {
                'required': True
            },
            'category': {
                'required': True
            },
            'description': {
                'required': True
            },
            'name': {
                'required': True
            },
            'logo': {
                'required': False,
                'allow_null': True
            }
        }

    def get_president_name(self, obj):
        """获取社团会长名称"""
        president = obj.members.filter(role='president').first()
        return president.user.username if president else None

    def get_activity_count(self, obj):
        """获取社团举办的活动数量"""
        return obj.activities.filter(status__in=['published', 'registration_open', 'ongoing', 'completed']).count()

    def validate_contact_phone(self, value):
        """验证联系电话格式"""
        import re
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("请输入正确的11位手机号码")
        return value


class ClubDetailSerializer(serializers.ModelSerializer):
    """社团详情序列化器"""
    president = serializers.SerializerMethodField()
    vice_presidents = serializers.SerializerMethodField()
    members = serializers.SerializerMethodField()
    recent_activities = serializers.SerializerMethodField()

    class Meta:
        model = Club
        fields = [
            'id', 'name', 'description', 'logo', 'category', 'founded_date',
            'member_count', 'contact_person', 'contact_phone', 'contact_email',
            'status', 'is_verified', 'created_at', 'updated_at',
            'president', 'vice_presidents', 'members', 'recent_activities'
        ]

    def get_president(self, obj):
        """获取社团会长信息"""
        president = obj.members.filter(role='president').first()
        if president:
            return {
                'id': president.user.id,
                'username': president.user.username,
                'nickname': president.user.nickname,
                'avatar': president.user.avatar.url if president.user.avatar else None
            }
        return None

    def get_vice_presidents(self, obj):
        """获取副会长信息列表"""
        vice_presidents = obj.members.filter(role='vice_president')
        return [{
            'id': vp.user.id,
            'username': vp.user.username,
            'nickname': vp.user.nickname,
            'avatar': vp.user.avatar.url if vp.user.avatar else None
        } for vp in vice_presidents]

    def get_members(self, obj):
        """获取社团成员数量统计"""
        return {
            'total': obj.member_count,
            'president': obj.members.filter(role='president').count(),
            'vice_president': obj.members.filter(role='vice_president').count(),
            'officer': obj.members.filter(role='officer').count(),
            'member': obj.members.filter(role='member').count()
        }

    def get_recent_activities(self, obj):
        """获取社团最近的3个活动"""
        activities = obj.activities.filter(
            status__in=['published', 'registration_open', 'ongoing', 'completed']
        ).order_by('-created_at')[:3]
        return ActivityListSerializer(activities, many=True).data


class ClubMemberSerializer(serializers.ModelSerializer):
    """社团成员序列化器"""
    user_info = UserBriefSerializer(source='user', read_only=True)
    club_name = serializers.CharField(source='club.name', read_only=True)

    class Meta:
        model = ClubMember
        fields = ['id', 'club', 'club_name', 'user', 'user_info', 'role', 'join_date', 'is_active']
        read_only_fields = ['id', 'join_date']


class ActivityListSerializer(serializers.ModelSerializer):
    """活动列表序列化器"""
    club_name = serializers.CharField(source='club.name', read_only=True)
    organizer_name = serializers.CharField(source='organizer.username', read_only=True)
    participant_count = serializers.IntegerField(read_only=True)
    is_registered = serializers.SerializerMethodField()

    class Meta:
        model = Activity
        fields = [
            'id', 'title', 'club', 'club_name', 'organizer', 'organizer_name',
            'activity_type', 'status', 'start_time', 'end_time', 'location',
            'participant_count', 'max_participants', 'is_registered', 'created_at'
        ]
        read_only_fields = ['id', 'created_at', 'participant_count']

    def get_is_registered(self, obj):
        """检查当前用户是否已报名"""
        request = self.context.get('request')
        if request and request.user and hasattr(request.user, 'is_authenticated') and request.user.is_authenticated:
            return ActivityRegistration.objects.filter(
                user=request.user,
                activity=obj
            ).exists()
        return False


class ActivityCreateSerializer(serializers.ModelSerializer):
    """创建活动序列化器"""
    # 允许提交club_id
    # 配置灵活的日期时间格式，同时支持带秒和不带秒的格式
    registration_deadline = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', input_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M'])
    start_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', input_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M'])
    end_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', input_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M'])
    class Meta:
        model = Activity
        fields = [
            'title', 'description', 'club', 'activity_type', 
            'start_time', 'end_time', 'location', 'registration_deadline', 
            'max_participants', 'is_free', 'fee', 'allow_guest', 'require_approval'
        ]


class ActivityImageSerializer(serializers.ModelSerializer):
    """活动图片序列化器"""
    image = serializers.ImageField(read_only=True)
    
    class Meta:
        model = ActivityImage
        fields = ['id', 'image', 'order', 'created_at']

class ActivityDetailSerializer(serializers.ModelSerializer):
    """活动详情序列化器"""
    club = ClubSerializer(read_only=True, allow_null=True)
    organizer_info = UserBriefSerializer(source='organizer', read_only=True)
    current_participants = serializers.IntegerField(read_only=True)
    is_registered = serializers.SerializerMethodField()
    is_signed_up = serializers.SerializerMethodField()
    images = ActivityImageSerializer(many=True, read_only=True)
    registration_deadline = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
    start_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
    end_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = Activity
        fields = [
            'id', 'title', 'description', 'club', 'organizer', 'organizer_info',
            'activity_type', 'status', 'start_time', 'end_time', 'location',
            'registration_deadline', 'current_participants', 'max_participants',
            'is_free', 'fee', 'allow_guest', 'require_approval', 'is_registered', 'is_signed_up', 'created_at', 'updated_at',
            'images'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at', 'current_participants']

    def get_is_registered(self, obj):
        """检查当前用户是否已报名"""
        return self.get_is_signed_up(obj)
    
    def get_is_signed_up(self, obj):
        """检查当前用户是否已报名(兼容前端字段名)"""
        request = self.context.get('request')
        if request and request.user and hasattr(request.user, 'is_authenticated') and request.user.is_authenticated:
            return ActivityRegistration.objects.filter(
                user=request.user,
                activity=obj
            ).exists()
        return False


class ActivityRegistrationSerializer(serializers.ModelSerializer):
    """活动报名序列化器"""
    user_info = UserBriefSerializer(source='user', read_only=True)
    activity_title = serializers.CharField(source='activity.title', read_only=True)

    class Meta:
        model = ActivityRegistration
        fields = [
            'id', 'activity', 'activity_title', 'user', 'user_info',
            'registered_at', 'status', 'contact_phone', 'special_requirements'
        ]
        read_only_fields = ['id', 'user', 'registered_at']

    def validate_activity(self, value):
        """验证活动是否可报名"""
        if value.status != 'registration_open':
            raise serializers.ValidationError("该活动未开放报名")
        return value

    def validate(self, data):
        """验证用户是否已报名"""
        user = self.context['request'].user
        activity = data['activity']
        if ActivityRegistration.objects.filter(user=user, activity=activity).exists():
            raise serializers.ValidationError("您已报名该活动")
        return data


# 为了保持兼容性，保留原有的序列化器名称
ActivitySerializer = ActivityDetailSerializer